$(function(){
    getInstancesOfUserInDataBase();//同步数据库中的虚拟机

    $.ajax({													// 请求MD5
        cache: false,
        url: "instance/getSimpleMd5",
        data: "",
        type: "POST",
        dataType: "text",
        success: function (md5) {
            if(md5.length===10) {
                webSocketSet(md5.substring(1,9));
            }
            else {
                webSocketSet(md5);
            }
        }
    });
});
function webSocketSet(md5) {

    var wsPath = "ws://59.69.101.206:30480/cloud";
    var webSocket = new WebSocket(wsPath + '/websocket/'+ md5);
    webSocket.onerror = function (event) {
    };
    webSocket.onopen = function (event) {
        console.log("open");
    };
    webSocket.onmessage = function (event) {
        console.log(event.data);
        var json = JSON.parse(event.data);
        switch (json.event){
            case "create": {
                if(json.result==="200"){
                    addRow("instanceTable",json);
                }else {
                    layer.msg(json.result,{icon:5,time:2000});
                }
            }break;
            case "delete":{
                if(json.result==="200"){
                    deleteRow("instanceTable",json);
                }else {
                    layer.msg(json.result,{icon:5,time:2000});
                }
            }break;
            case "getUrl":{
                showMsg(json,json.instance_id+"同步成功，点击实例即可访问您的虚拟机啦!");
            }break;
            case "getStatus":{
                showMsg(json,json.instance_id+"同步状态成功!");
            }break;
            case "start":{
                showMsg(json,json.instance_id+"启动成功!");
            }break;
            case "stop":{
                showMsg(json,json.instance_id+"关机成功!");
            }break;
            case "reboot":{
                showMsg(json,json.instance_id+"重启成功!");
            }break;
            case "suspend":{
                showMsg(json,json.instance_id+"挂起成功!");
            }break;
            case "resume":{
                showMsg(json,json.instance_id+"恢复成功!");
            }break;
            case "pause":{
                showMsg(json,json.instance_id+"暂停成功!");
            }break;
            case "unpause":{
                showMsg(json,json.instance_id+"继续运行!");
            }break;
            case "lock":{
                showMsg(json,json.instance_id+"被锁住，解锁才能有其他操作哦!");
            }break;
            case "unlock":{
                showMsg(json,json.instance_id+"解锁成功!")
            }break;
            default:
                break;
        }
    };
}
function showMsg(json,msg) {
    if(json.result==="200"){
        layer.msg(msg,{icon:6,time:2000});
        updateRow(json);
    }else {
        layer.msg(json.result,{icon:5,time:2000});
    }
}
function getInstancesOfUserInDataBase() {
    $.ajax({
        url: "instance/getInstancesOfUserInDataBase",
        type: "POST",
        data: "",
        dataType: "json",
        success: function (jsonArray) {
            console.log(jsonArray);
            for(var i=0; i!==jsonArray.length;++i) {
                addRow("instanceTable",jsonArray[i]);
            }
        }
    });
}
function synSingleStatus(instance_id) {
    $.ajax({
        url: "instance/syncSingleStatus",
        type: "POST",
        data: {
            instance_id:instance_id
        },
        dataType: "json",
        success: function (jsonData) {
            showMsg(jsonData,jsonData.instance_id+"同步状态成功!");
        }
    });
}
function synSingleUrl(instance_id) {
    $.ajax({
        url: "instance/syncSingleUrl",
        type: "POST",
        data:{
            instance_id:instance_id
        },
        dataType: "json",
        success: function (jsonData) {
            showMsg(jsonData,jsonData.instance_id+"同步成功，点击实例即可访问您的虚拟机啦!");
        }
    });
}
function operateInstance(rowObject,option) {
    var instanceName = rowObject.childNodes[1].childNodes[0].innerText;
    var instanceId = rowObject.id;
    switch (option){
        case "delete":{
            deleteSingleInstance(instanceName,instanceId);
        }break;
        case "start":{
            operateAndPost(instanceName,instanceId,"start","启动");
        }break;
        case "stop":{
            confirmOperateAndPost(instanceName,instanceId,"stop","关闭");
        }break;
        case "suspend":{
            confirmOperateAndPost(instanceName,instanceId,"suspend","挂起");
        }break;
        case "resume":{
            operateAndPost(instanceName,instanceId,"resume","恢复");
        }break;
        case "pause":{
            confirmOperateAndPost(instanceName,instanceId,"pause","暂停");
        }break;
        case "unpause":{
            operateAndPost(instanceName,instanceId,"unpause","继续");
        }break;
        case "reboot":{
            confirmOperateAndPost(instanceName,instanceId,"reboot","重启");
        }break;
        case "lock":{
            lockInstance(instanceName,instanceId);
        }break;
        case "unlock":{
            unLockInstance(instanceName,instanceId);
        }break;
        default:
            return;
    }
}
function lockInstance(instanceName,instanceId) {

    layer.confirm('确定要锁定'+instanceName+"?虚拟机的状态将会被锁定哦", {icon: 6, title:'提示'}, function(index) {
        $.ajax({
            url: "instance/operateSingle",
            type: "POST",
            data: {
                instance_id:instanceId,
                operate: "lock"
            },
            dataType: "json",
            success: function (json) {
                showMsg(json,"成功锁定"+instanceName);
            }
        });
        layer.close(index);
        layer.msg("正在锁定" + instanceName, {
            icon: 6,//笑脸
            time: 2000 //2秒关闭（如果不配置，默认是3秒）
        });
    });
}
function unLockInstance(instanceName,instanceId) {
    $.ajax({
        url: "instance/operateSingle",
        type: "POST",
        data: {
            instance_id:instanceId,
            operate: "unlock"
        },
        dataType: "json",
        success: function (json) {
            showMsg(json,"成功解锁"+instanceName);
        }
    });
    layer.msg("正在解锁" + instanceName, {
        icon: 6,//笑脸
        time: 2000 //2秒关闭（如果不配置，默认是3秒）
    });
}
function deleteSingleInstance(instanceName,instanceId) {
    layer.confirm('确定要删除'+instanceName+"?", {icon: 6, title:'提示'}, function(index) {
        $.ajax({
            url: "instance/operateSingle",
            type: "POST",
            data: {
                instance_id:instanceId,
                operate: "delete"
            },
            dataType: "json",
            success: function (json) {
                deleteRow("instanceTable",json);
            }
        });
        layer.close(index);
        layer.msg("正在删除" + instanceName, {
            icon: 6,//哭脸
            time: 2000 //2秒关闭（如果不配置，默认是3秒）
        });
    });
}
function confirmOperateAndPost(instanceName,instanceId,option,optionInChinese) {
    layer.confirm('确定要'+optionInChinese+instanceName+"?", {icon: 6, title:'提示'}, function(index) {
        $.ajax({
            url: "instance/operateSingle",
            type: "POST",
            data: {
                instance_id:instanceId,
                operate: option
            },
            dataType: "json",
            success: function (json) {
               showMsg(json,"成功"+optionInChinese+instanceName);
            }
        });
        layer.close(index);
        layer.msg("正在"+optionInChinese + instanceName, {
            icon: 6,//笑脸
            time: 2000 //2秒关闭（如果不配置，默认是3秒）
        });
    });
}
function operateAndPost(instanceName,instanceId,option,optionInChinese) {
    $.ajax({
        url: "instance/operateSingle",
        type: "POST",
        data: {
            instance_id:instanceId,
            operate: option
        },
        dataType: "json",
        success: function (json) {
            showMsg(json,"成功"+optionInChinese+instanceName);
        }
    });
    layer.msg("正在"+optionInChinese + instanceName, {
        icon: 6,//笑脸
        time: 2000 //2秒关闭（如果不配置，默认是3秒）
    });
}
//多台实例一起
function delCheckedInstance(msg) {
    var instanceIdArray = getRowIdArrayOfCheckedVHost();
    $.ajax({
        url: "instance/deleteMulti",
        type: "POST",
        data: {
            instanceIdArray:JSON.stringify(instanceIdArray)
        },
        dataType: "text",
        success: function (result) {
            if (result === "200") {
                layer.msg("正在删除" + msg+"请耐心等待...", {
                    icon: 6,//哭脸
                    time: 2000 //2秒关闭（如果不配置，默认是3秒）
                });
            }
            else {
                layer.msg("删除失败!服务器开小差啦", {
                    icon: 5,//哭脸
                    time: 2000 //2秒关闭（如果不配置，默认是3秒）
                });
            }
        }
    });
}

